package com.cjkj.equipment.service.impl;

import com.cjkj.common.utils.DateUtils;
import com.cjkj.equipment.domain.EquipmentTj03MonitorRecordsEcg;
import com.cjkj.equipment.domain.EquipmentTj03MonitorRecordsHr;
import com.cjkj.equipment.domain.vo.EcgVo;
import com.cjkj.equipment.mapper.EquipmentTj03MonitorRecordsEcgMapper;
import com.cjkj.equipment.mapper.EquipmentTj03MonitorRecordsHrMapper;
import com.cjkj.equipment.service.EquipmentTj03MonitorRecordsEcgService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class EquipmentTj03MonitorRecordsEcgServiceImpl implements EquipmentTj03MonitorRecordsEcgService {

    @Resource
    private EquipmentTj03MonitorRecordsEcgMapper ecgMapper;
    @Resource
    private EquipmentTj03MonitorRecordsHrMapper hrMapper;

    @Override
    public List<EcgVo> getEcgDatas(String equipmentNo, Date startTime) {

        // 查询最新一次心率数据
        EquipmentTj03MonitorRecordsHr lastOneHrData = hrMapper.selectLastHrDataByEquipment(equipmentNo, startTime);
        if(lastOneHrData == null) {
            return Collections.emptyList();
        }

        // 5分钟的秒数
        int tenMinutesAgoSecond = 300;
        // 最新一条心电数据的时间毫秒数
        long lastDataMillisecond = lastOneHrData.getCreateTime().getTime();
        // 5分钟前的时间毫秒数
        long tenMinutesAgoMillisecond = lastDataMillisecond - (tenMinutesAgoSecond * 1000L);
//        System.out.println("心电开始时间：" + DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss.SSS", new Date(tenMinutesAgoMillisecond))+"（"+ tenMinutesAgoMillisecond +"）");
//        System.out.println("心电结束时间：" + DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss.SSS", new Date(lastDataMillisecond))+"（"+ lastDataMillisecond +"）");

        // 查询最新心电数据
        List<EquipmentTj03MonitorRecordsEcg> ecgList = ecgMapper.selectEcgDataByEquipment(equipmentNo, startTime, lastOneHrData.getCreateTime(), new Date(tenMinutesAgoMillisecond));
        if(ecgList == null || ecgList.isEmpty()) {
            return Collections.emptyList();
        }

        // 拿出第一条心电数据
        EquipmentTj03MonitorRecordsEcg firstOneRecord = ecgList.get(ecgList.size() - 1);
        long firstOneRecordTime = firstOneRecord.getCreateTime().getTime();

        long start = tenMinutesAgoMillisecond - (tenMinutesAgoMillisecond % 1000);
        // 如果第一条心电数据的监测时间在5分钟之内，则从第一条心电数据开始
        if(firstOneRecordTime > tenMinutesAgoMillisecond) {
            start = firstOneRecordTime - (firstOneRecordTime % 1000);
        }

        int c = Integer.parseInt(String.valueOf ((lastDataMillisecond - firstOneRecordTime) / 1000));
        List<EcgVo> ecgDatas = new ArrayList<>();
        for (int i = 0; i < c; i++) {
            long finalStart = start;
            // 获取一秒内的心电数据
            List<EquipmentTj03MonitorRecordsEcg> oneSecondData = ecgList.stream()
                    .filter(ecg -> ecg.getCreateTime().getTime() >= finalStart && ecg.getCreateTime().getTime() < finalStart + 1000)
                    .sorted(Comparator.comparing(EquipmentTj03MonitorRecordsEcg::getCreateTime))
                    .collect(Collectors.toList());

            List<Integer> oneSecondEcgDatas = getIntegers(oneSecondData);
//            System.out.println("时间："+ DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss.SSS", new Date(start))+"，范围：["+start+","+(start + 1000)+")，数据长度："+oneSecondEcgDatas.size()+"，数据：" + oneSecondEcgDatas);

            // 组装心电数据
            for (int j = 0; j < oneSecondEcgDatas.size(); j++) {
                EcgVo ecgVo = new EcgVo();
                ecgVo.setTime(start + (j * 4L));
                ecgVo.setValue(oneSecondEcgDatas.get(j));
                ecgDatas.add(ecgVo);
            }

            start += 1000L;
        }

        return ecgDatas;
    }

    private static List<Integer> getIntegers(List<EquipmentTj03MonitorRecordsEcg> oneSecondData) {
        List<Integer> oneSecondEcgDatas = new ArrayList<>();
        if(! oneSecondData.isEmpty()) {
            for (EquipmentTj03MonitorRecordsEcg ecg : oneSecondData) {
                String[] split = ecg.getEcgData().split(",");
//                System.out.println("时间："+ DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss.SSS", new Date(ecg.getCreateTime())) + "，数据长度："+split.length + "，解析数据："+ecg.getEcgData());
                for (String s : split) {
                    oneSecondEcgDatas.add(Integer.parseInt(s));
                }
            }
        }

        int allDataSize = 250;
        // 数据不齐的时候补0
        if (oneSecondEcgDatas.size() < allDataSize) {
            int zeroFillNum = allDataSize - oneSecondEcgDatas.size();
            for (int j = 0; j < zeroFillNum; j++) {
                oneSecondEcgDatas.add(0);
            }
        }
        return oneSecondEcgDatas;
    }
}
